import { GaugeOptions } from '../models/options/gaugeOptions';
import { BarOptions } from '../models/options/barOptions';
import { Series } from '../models/series';
import { BarSeries } from '../models/barSeries';

import { PanelOptions, Pod } from '../types';

import { DataProcessor } from '../grafana/data_processor';

import { ChartwerkGaugePod } from '@chartwerk/gauge-pod';
import { ChartwerkBarPod } from '@chartwerk/bar-pod';

import { PanelData, TimeRange, PanelProps } from '@grafana/data';
import { VizLegend } from '@grafana/ui';
import { LegendDisplayMode } from '@grafana/schema';

import React, { useRef } from 'react';
import { css } from 'emotion';
import * as _ from 'lodash';

interface Props extends PanelProps<PanelOptions> {}

export function Panel({ options, data, width, height, timeRange, onChangeTimeRange }: Props) {
  const grafanaSeriesList = getGrafanaSeriesList(data, timeRange);
  let chartContainer = useRef(null);

  // we request animation frame here because we need an existing DOM-element at the moment we render the pod
  window.requestAnimationFrame(() => {
    let pod;
    switch (options.visualizationType) {
      case Pod.GAUGE:
        const series = new Series(grafanaSeriesList, options.gauge.value).getChartwerkSeries();
        const chartwerkGaugeOptions = new GaugeOptions(grafanaSeriesList, options).getChartwerkOptions();
        pod = new ChartwerkGaugePod((chartContainer as any).current, series, chartwerkGaugeOptions);
        break;
      case Pod.BAR:
        const barSeries = new BarSeries(grafanaSeriesList).getChartwerkSeries();
        const chartwerkBarOptions = new BarOptions(grafanaSeriesList, onChangeTimeRange).getChartwerkOptions();
        pod = new ChartwerkBarPod((chartContainer as any).current, barSeries, chartwerkBarOptions);
        break;
      default:
        throw new Error(`Unknown visualization type: ${options.visualizationType}`);
    }
    pod.render();
  });

  const isLinkActive = !_.isEmpty(options.gauge.link);
  const chartClickHandler = (event: React.MouseEvent<HTMLDivElement>) => {
    event.preventDefault();
    if (!isLinkActive) {
      return;
    }
    window.open(options.gauge.link, '_self');
  };
  const legendItems = _.map(grafanaSeriesList, (serie) => {
    return {
      label: serie.alias,
      color: serie.color,
      yAxis: 1,
    };
  });
  const chartHeight = options.visualizationType !== Pod.GAUGE ? height - 20 : height;
  return (
    <div>
      <div
        ref={chartContainer}
        className={css`
          width: ${width}px;
          height: ${chartHeight}px;
          cursor: ${isLinkActive ? 'pointer' : 'default'};
        `}
        onClick={chartClickHandler}
      ></div>
      {options.visualizationType !== Pod.GAUGE && (
        <VizLegend placement={'bottom'} items={legendItems} displayMode={LegendDisplayMode.List} />
      )}
    </div>
  );
}

function getGrafanaSeriesList(grafanaData: PanelData, timeRange: TimeRange): any[] {
  const processor = new DataProcessor({});
  return processor.getSeriesList({
    dataList: grafanaData.series,
    range: timeRange,
  });
}
